package com.pro01.backend.controller;

import com.pro01.backend.pojo.Promotion2;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.Promotion2Service;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Map;

@RestController
@RequestMapping("/admin/torrents/promotions2")
public class AdminPromotion2Controller {

    @Autowired
    private Promotion2Service promotion2Service;

    // 管理员设置促销
    @PostMapping
    public Result<?> createPromotion(@RequestBody Map<String, Object> body, HttpServletRequest request) {
        if (!"ADMIN".equals(TokenUtil.getRole(request))) {
            return Result.error("无权限，仅管理员可用");
        }

        try {
            Long torrentId = Long.valueOf(body.get("torrentId").toString());
            String promotionType = body.get("promotionType").toString();
            Integer durationMinutes = Integer.valueOf(body.get("durationMinutes").toString());

            if (torrentId == null || promotionType == null || durationMinutes == null || durationMinutes <= 0) {
                return Result.error("参数不合法");
            }

            Promotion2 promotion = new Promotion2();
            promotion.setTorrentId(torrentId);
            promotion.setPromotionType(promotionType);

            Timestamp now = new Timestamp(System.currentTimeMillis());
            promotion.setStartTime(now);
            promotion.setEndTime(new Timestamp(now.getTime() + durationMinutes * 60_000L)); // ✅ 分钟转毫秒

            boolean success = promotion2Service.createPromotion(promotion);
            return success ? Result.success("促销创建成功") : Result.error("促销创建失败");

        } catch (Exception e) {
            return Result.error("参数处理异常：" + e.getMessage());
        }
    }


    // 管理员取消促销
    @DeleteMapping("/{torrentId}")
    public Result<?> cancelPromotion(@PathVariable Long torrentId, HttpServletRequest request) {
        if (!"ADMIN".equals(TokenUtil.getRole(request))) {
            return Result.error("无权限，仅管理员可用");
        }

        boolean success = promotion2Service.cancelPromotion(torrentId);
        return success ? Result.success("促销已取消") : Result.error("取消失败或该种子无促销");
    }



}
